from typing import override
from rest_framework.decorators import action
from rest_framework.viewsets import ViewSet,ModelViewSet,ReadOnlyModelViewSet
from rest_framework import viewsets,mixins
from rest_framework.response import Response
from Drf_api.paginations import ProductPageNumberPagination
from product.models import Product,Review
from Apis.serializers import ProductModelSerializer,ReviewModelSerializer

from django_filters.rest_framework import DjangoFilterBackend  # 用于过滤数据

class ProductViewset(ViewSet):
    
    # 商品列表
    
    def list(self,request):
        queryset = Product.objects.filter(is_active=True)
        serializer = ProductModelSerializer(queryset,many=True)
        return Response({"message":"success","data":serializer.data})
    
    # 商品详情   
    
    def retrieve(self,request,pk=None):
        try:
            products = Product.objects.get(pk=pk)
            serializer = ProductModelSerializer(products,many=False)
            return Response({"message":"success","data":serializer.data})
        except Product.DoesNotExist:
            return Response({"message":"商品不存在！"},status=404)
        
    # 商品创建
    def create(self,request):
        try:
            serializer = ProductModelSerializer(data=request.data)
            if serializer.is_valid(raise_exception=True):
                serializer.save()
                return Response({"message":"success","data":serializer.data},status=201)
        except Exception as e:
            return Response(serializer.errors,status=400)
        
    # 商品更新  全量更新
    def update(self,request,pk=None):
        try:
            products = Product.objects.get(pk=pk)
            serializer = ProductModelSerializer(products,data=request.data)
            if serializer.is_valid(raise_exception=True):
                serializer.save()
                return Response({"message":"success","data":serializer.data},status=200)
        except Product.DoesNotExist:
            return Response({"message":"商品不存在！"},status=404)
        
    # 商品更新  部分更新（patch）
    def partial_update(self,request,pk=None):
        try:
            products = Product.objects.get(pk=pk)
            serializer = ProductModelSerializer(products,data=request.data,partial=True)
            if serializer.is_valid(raise_exception=True):
                serializer.save()
                return Response({"message":"success","data":serializer.data},status=200)
        except Product.DoesNotExist:
            return Response({"message":"商品不存在！"},status=404)
        
    # 商品删除
    def destroy(self,request,pk=None):
        try:
            products = Product.objects.get(pk=pk)
            products.delete()
            return Response({"message":"success"},status=204)
        except Product.DoesNotExist:
            return Response({"message":"商品不存在！"},status=404)
        
 # ViewSet视图集的继承关系：ViewSet -> APIView -> View -> object
 
 # GenericViewSet视图集的继承关系：GenericViewSet -> ViewSetMixin -> GenericAPIView -> APIView -> View -> object
class ProductGenriceViewset(viewsets.GenericViewSet,mixins.ListModelMixin,mixins.RetrieveModelMixin,mixins.CreateModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin):
     queryset = Product.objects.all()
     serializer_class = ProductModelSerializer
   
# 具备全部的CRUD功能的视图集
class ProductModelViewset(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductModelSerializer  #1
    
    
    # 数据查询完了，再过滤数据
    # 配置过滤器后端
    filter_backends = [DjangoFilterBackend]  # 过滤    3
    filterset_fields = ["product_name","price"]  # 过滤字段 4
    #-------------------------------------------------------
    # 分页器类，用于分页数据
    pagination_class = ProductPageNumberPagination #2
    #------------------------------------------------------
    # 重写删除方法，逻辑删除

    def perform_destroy(self, instance):
        instance.is_active = False
        instance.save()        
    
    
    # 通过@action装饰器来添加自定义的action方法
    @action(
        methods=["GET"],
        detail=True,
        url_path="review",
        name="Product Reviews",  # 显式命名
        description="获取商品的所有评论"   #显式描述
        )
    def reviews(self,request,pk=None):  # 之前用review,
       """获取商品的所有评论"""
       # 获取当前商品对象
       product = self.get_object()
       reviews = product.review_set.filter(is_active=True)
       serializer = ReviewModelSerializer(reviews,many=True)
       return Response({"message":"success","data":serializer.data})
    
# 具备只读功能的视图集
class ProductReadOnlyModelViewset(viewsets.ReadOnlyModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductModelSerializer
    

   
   
    
    
  
    
